<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="运营商公司名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运营商编码" prop="deptCode">
        <el-input
          v-model="queryParams.deptCode"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-cascader
          style="width: 200px"
          size="large"
          :options="options"
          v-model="queryParams.city"
          :show-all-levels="true"
          :props="cityOneProps"
          @change="handleChange"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="运营城市" prop="cityRange">
        <el-cascader
          style="width: 200px"
          size="large"
          :options="options"
          v-model="queryParams.cityRange"
          :show-all-levels="true"
          :props="cityOneProps"
          @change="handleChange"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="负责人姓名" prop="leader">
        <el-input
          v-model="queryParams.leader"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="dict in dict.type.jazx_clientcompany_enablestatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd">新建子运营商 </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="运营商公司名称" width="260"></el-table-column>
      <el-table-column prop="deptCode" label="运营商编码" width="100"></el-table-column>
      <el-table-column prop="city" label="所在城市" width="180"></el-table-column>
      <el-table-column
        prop="cityRange"
        label="运营城市范围"
        :show-overflow-tooltip="true"
        width="260"
      ></el-table-column>
      <el-table-column prop="leader" label="负责人" width="100"></el-table-column>
      <el-table-column prop="phone" label="负责人联系方式" width="110"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.jazx_clientcompany_enablestatus"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column prop="status" label="状态" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-col v-if="scope.row.status === '1'"  style="width: 10px;height: 10px;border-radius: 50%;background-color: #e64242;margin-top: 5px;left: 45px;"></el-col>-->
      <!--          <el-col v-if="scope.row.status === '0'" style="width: 10px;height: 10px;border-radius: 50%;background-color: #58de35;margin-top: 5px;left: 45px;"></el-col>-->
      <!--          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            >编辑
          </el-button>
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            @click="handleDisable(scope.row)"
            >禁用
          </el-button>
          <el-button
            v-if="scope.row.status === '1'"
            size="mini"
            type="text"
            @click="handleEnable(scope.row)"
            >启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="运营商公司名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="运营商编码" prop="deptCode">
              <el-input v-model="form.deptCode" placeholder="请输入" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="所在城市" prop="cityArray">
            <el-cascader
              style="width: 100%"
              size="large"
              :options="options"
              v-model="form.city"
              :show-all-levels="true"
              :props="cityOneProps"
              @change="handleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="运营城市范围" prop="cityRangeArray">
            <el-cascader
              style="width: 100%"
              size="large"
              :options="options"
              v-model="form.cityRangeArray"
              :show-all-levels="true"
              :props="cityTwoProps"
              collapse-tags
              @change="handleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="负责人姓名" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="负责人联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="!this.form.deptId" label="超级管理员账号" required>
          <div style="line-height: 50px">
            <el-input v-model="form.userName" placeholder="请输入" />
            <el-input v-model="form.phonenumber" placeholder="请输入" />
          </div>
          <el-button
            style="margin-left: 415px; margin-top: -140px; position: absolute; color: #409eff"
            size="mini"
            @click="handlecheck"
            >同步负责人信息</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, addDept, updateDept, updateStatus } from '@/api/operate/operator';
import { provinceAndCityData, CodeToText } from 'element-china-area-data';
export default {
  name: 'OperateOperator',
  dicts: ['jazx_clientcompany_enablestatus', 'sys_dept_type'],
  data() {
    return {
      //省市选择
      cityOneProps: { emitPath: false },
      cityTwoProps: { multiple: true, emitPath: false },
      options: provinceAndCityData,
      selectedOptions: ['110100', '120100'],
      city: [],
      isExpandAll: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        deptCode: undefined,
        city: [],
        cityRange: [],
        leader: undefined,
        phone: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptName: [{ required: true, message: '运营商公司名称不能为空', trigger: 'blur' }],
        deptCode: [{ required: true, message: '运营商编码不能为空', trigger: 'blur' }],
        cityArray: [{ required: true, message: '所在城市不能为空', trigger: 'blur' }],
        cityRangeArray: [{ required: true, message: '运营城市范围不能为空', trigger: 'blur' }],
        leader: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        phone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的负责人手机号码',
            trigger: 'blur',
          },
        ],
        userName: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的负责人手机号码',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then((response) => {
        console.log(response)
        response.data.forEach((item) => {
          if (item.city !== null && item.city !== '') {
            item.city = this.watchDataTrm(item.city, true);
          }
          if (item.cityRange !== null && item.cityRange !== '') {
            let cityRange = item.cityRange.split(',');
            cityRange = cityRange.map((item) => {
              item = this.watchDataTrm(item);
              return item;
            });
            item.cityRange = cityRange.join('，');
          }
        });
        this.deptList = this.handleTree(response.data, 'deptId');
        this.loading = false;
      });
    },
    /**
     * ===================================================================
     * ===========================城市数据转换==============================
     * ===================================================================
     */
    // 检测数据类型并转换
    watchDataTrm(value, isShowAll) {
      if (Object.prototype.toString.call(value) === '[object String]') {
        let buffer = '';
        let dictData = '';
        buffer = value.split(',');
        dictData = this.findDistrict(this.options, buffer[buffer.length - 1], isShowAll);
        dictData = dictData ? dictData.join(' / ') : '';
        return dictData;
      } else if (Object.prototype.toString.call(value) === '[object Array]') {
        let dictData = '';
        dictData = this.findDistrict(this.options, value[value.length - 1], isShowAll);
        dictData = dictData ? dictData.join('/') : '';
        return dictData;
      }
      return '--';
    },
    // 从树中寻找对应的键值对
    findDistrict(list, id, isShowAll) {
      // 获取某一项的所有父节点的label值 list为树形结构的数据 id为回显节点的标识
      for (let i in list) {
        if (list[i].value == id) {
          //这里的list[i].id中的id根据你的需求可进行改变
          //查询到就返回该数组对象的value
          return [list[i].label];
        }
        if (list[i].children) {
          let node = this.findDistrict(list[i].children, id);
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            if (isShowAll) {
              node.unshift(list[i].label);
              return node;
            } else {
              if (node.includes('市辖区')) {
                node.pop();
                node.unshift(list[i].label);
              }
              return node;
            }
          }
        }
      }
    },
    /**
     * ===================================================================
     * ===================================================================
     * ===================================================================
     */
    handleChange(value) {
      console.log(value);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        deptName: undefined,
        deptCode: undefined,
        cityArray: [],
        cityRangeArray: [],
        leader: undefined,
        phone: undefined,
        userName: undefined,
        phonenumber: undefined,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = '新建运营商';
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改运营商';
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.parentId = 100;
      const cityArray = [];
      cityArray.push(this.form.city);
      this.form.cityArray = cityArray;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handlecheck() {
      this.form.userName = this.form.leader;
      this.form.phonenumber = this.form.phone;
    },
    handleEnable(row) {
      this.$modal
        .confirm('是否确认启用名称为"' + row.deptName + '"的数据项？')
        .then(function () {
          const params = {
            deptId: row.deptId,
            status: '0',
          };
          return updateStatus(params);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('启用成功');
        })
        .catch(() => {});
    },
    /** 禁用按钮操作 */
    handleDisable(row) {
      this.$modal
        .confirm('是否确认禁用名称为"' + row.deptName + '"的数据项？')
        .then(function () {
          const params = {
            deptId: row.deptId,
            status: '1',
          };
          return updateStatus(params);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('禁用成功');
        })
        .catch(() => {});
    },
  },
};
</script>
